package de.playmee.views;

import java.util.ArrayList;

import de.playmee.Channel;
import de.playmee.R;
import de.playmee.handler.ChannelHandler;
import android.content.Context;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class SimpleChannelViewAdapter extends BaseAdapter {
	
	// context needed to create new views
	private Context context;
	
	// list of all channels to display
	// more complex views maybe need another way to store channels
	private ArrayList<Channel> channels = new ArrayList<Channel>();
	
	// the height and weight of the channel image
	private final int imageSize;
	
	public SimpleChannelViewAdapter(Context context, ChannelHandler cHandler, String orderBy,
			int imageSize) {
		this.context = context;
		this.channels = cHandler.loadChannels(null, null, null, orderBy);
		this.imageSize = imageSize;
	}

	@Override
	public int getCount() {
		return channels.size();
	}

	@Override
	public Object getItem(int position) {
		return channels.get(position);
	}

	@Override
	public long getItemId(int position) {
		return channels.get(position).getId();
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		LinearLayout layout;
		
		if (convertView == null) {
			// if it's not recycled, initialize some attributes
			Channel channel = channels.get(position);
			String label = channel.getLabel();
			int image = channel.getImage();
			
			// vertical layout
			layout = new LinearLayout(context);
			layout.setOrientation(LinearLayout.VERTICAL);
			layout.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
			
			// image
			ImageView imageView = new ImageView(context);
			imageView.setLayoutParams(new GridView.LayoutParams(imageSize, imageSize));
			imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
			imageView.setPadding(8, 8, 8, 8);
			imageView.setImageResource(image);
			layout.addView(imageView);
			
			// text
			TextView textView = new TextView(context);
			textView.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
			textView.setText(label);
			textView.setTextColor(context.getResources().getColor(R.color.custom_theme_textcolor));
			layout.addView(textView);
		} else {
			layout = (LinearLayout) convertView;
		}
		
		return layout;
	}
}
